package com.siyoumi.app.modules.sh.service;

import com.siyoumi.app.entity.ShFund;
import com.siyoumi.app.modules.sh.vo.ShApiFundInfo;
import com.siyoumi.app.modules.sh.vo.ShFundData;
import com.siyoumi.app.service.ShFundService;
import com.siyoumi.component.LogPipeLine;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XHttpClient;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class SvcShFund {
    static public SvcShFund getBean() {
        return XSpringContext.getBean(SvcShFund.class);
    }

    static public ShFundService getApp() {
        return ShFundService.getBean();
    }

    public JoinWrapperPlus<ShFund> listQuery() {
        JoinWrapperPlus<ShFund> query = getApp().join();
        query.eq("fund_x_id", XHttpContext.getX());
        return query;
    }

    //导出config
    public String exportConfig() {
        JoinWrapperPlus<ShFund> query = listQuery();
        List<ShFund> list = getApp().list(query);
        List<ShFundData> listData = new ArrayList<>();
        for (ShFund entityFund : list) {
            listData.add(entityFund.fundData());
        }

        return XJson.toJSONString(listData);
    }

    @Transactional(rollbackFor = Exception.class)
    public XReturn delete(List<String> ids) {
        getApp().delete(ids);

        return EnumSys.OK.getR();
    }


    /**
     * 基金信息
     * <p>
     * name：名称
     * fundcode：基金代码
     * gztime：更新时间
     * gsz：最新净值
     * gszzl：升降百分比
     * {'fundcode': '008929', 'name': '宏利消费红利指数C', 'jzrq': '2025-04-29', 'dwjz': '1.5122', 'gsz': '1.4953', 'gszzl': '-1.12', 'gztime': '2025-04-30 15:00'}
     */
    public ShApiFundInfo getApiFundInfo(String fundCode) {
        XValidator.isNullOrEmpty(fundCode, "miss fund_code");

        String apiUrl = XStr.format("https://fundgz.1234567.com.cn/js/{0}.js?rt=1746241232544", fundCode);
        XHttpClient client = XHttpClient.getInstance();
        String returnStr = client.get(apiUrl, null);
        if (XStr.isNullOrEmpty(returnStr)) {
            return new ShApiFundInfo();
        }
        LogPipeLine.of().setLogMsg(apiUrl);
        LogPipeLine.of().setLogMsg(returnStr);


        String jsonStr = returnStr.replace("jsonpgz(", "")
                .replace(");", "");
        return XJson.parseObject(jsonStr, ShApiFundInfo.class);
    }
}
